~ chicken-core (chicken-5) /manual/Getting started
Trap1[[tags: manual]]
2
3== Getting started
4
5CHICKEN is a compiler that translates Scheme source files into
6C, which in turn can be fed to a C compiler to generate a
7standalone executable. An interpreter is also available and can be
8used as a scripting environment or for testing programs before
9compilation.
10
11This chapter is designed to get you started with CHICKEN programming,
12describing what it is and what it will do for you, and covering basic
13use of the system. With almost everything discussed here, there is
14more to the story, which the remainder of the manual reveals. Here, we
15only cover enough to get you started. Nonetheless, someone who knows
16Scheme already should be able to use this chapter as the basis for
17writing and running small CHICKEN programs.
18
19=== Scheme
20
21Scheme is a member of the Lisp family of languages, of which Common
22Lisp, Emacs Lisp and Clojure are other widely-known members. As with
23Lisp dialects, Scheme features
24
25* a wide variety of programming paradigms, including imperative, functional, and object-oriented
26* a very simple syntax, based upon nested parenthesization
27* the ability to extend the language in meaningful and useful ways
28
29In contrast to Common Lisp, Scheme is very minimal, and tries to
30include only those features absolutely necessary in programming. In
31contrast to Emacs Lisp, Scheme is not anchored into a single program
32(Emacs), and has a more modern and elegant language design. In contrast
33to Clojure, Scheme provides only a very minimal set of concepts but allows
34them to be used in very general ways with few restrictions.
35
36Scheme is defined in a document called ''The Revised^5 Report on the
37Algorithmic Language Scheme'', or ''R5RS'' for short. (Yes, it really
38has been revised five times, so an expanded version of its name would
39be ''The Revised Revised Revised Revised Revised Report''.) A newer
40report, ''R6RS'', was
41released in 2007, but this report has attracted considerable
42controversy, and a number of Scheme implementations have chosen
43not to be compliant
44with it. Yet another report was released in 2013 ("R7RS"), that was
45less ambitious than R6RS and more minimal.
46
47CHICKEN fully complies with R5RS and, by using a separately available
48extension also with the "R7RS small" language.
49
50Even though Scheme is consciously minimalist, it is recognized that a
51language must be more than a minimal core in order to be
52useful. Accordingly, the Scheme community uses a process known as
53`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to
54define new language features. A typical Scheme system therefore
55complies with one of the Scheme reports plus some or all of the
56accepted SRFIs.
57
58A good starting point for Scheme knowledge is
59[[http://www.schemers.org]]. There you will find the defining reports,
60FAQs, lists of useful books and other resources, and the SRFIs.
61
62=== CHICKEN
63
64CHICKEN Scheme combines an optimising compiler with a reasonably fast
65interpreter. It supports almost all of R7RS and the important SRFIs.
66The compiler generates portable C code that supports tail recursion,
67first-class continuations and lightweight threads, and the interface to
68and from C libraries is flexible, efficient, and easy to use. There are
69hundreds of contributed CHICKEN libraries that make the programmer's
70task easier. The interpreter allows interactive use, fast prototyping,
71debugging, and scripting. The active and helpful CHICKEN community
72fixes bugs and provides support. Extensive documentation is supplied.
73
74CHICKEN was developed by Felix L. Winkelmann over the period from 2000
75through 2007. In early 2008, Felix
76asked the community to take over the responsibility of developing and
77maintaining the system, though he still takes a strong interest in it,
78and participates actively.
79
80CHICKEN includes
81
82* a Scheme interpreter that supports all of R5(7)RS Scheme, with
83 only a few relatively minor omissions, and with many extensions
84* a compatible compiler whose target is C, thus making porting to new
85 machines and architectures relatively straightforward
86* the C support allows Scheme code to include `embedded' C code,
87 thus making it easy to invoke host OS or library
88 functions
89* a framework for language extensions, library modules that broaden
90 the functionality of the system
91
92This package is distributed under the '''BSD license''' and as such is free
93to use and modify as long as the original authors are acknowledged.
94
95Scheme cognoscenti will appreciate the method of compilation and the
96design of the runtime-system, which follow closely Henry Baker's
97[[https://web.archive.org/web/20200223051632/http://home.pipeline.com/~hbaker1/CheneyMTA.html|CONS Should Not
98CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
99number of interesting properties.
100
101* Consing (creation of data on the heap) is inexpensive,
102 because a generational garbage collection scheme is used in combination
103 with allocating on the C stack, in which short-lived data structures are reclaimed
104 extremely quickly.
105
106* Moreover, {{call-with-current-continuation}} involves only minimal
107 overhead and CHICKEN does not suffer under any performance penalties if
108 first-class continuations are used in complex ways.
109
110The generated C code fully supports tail-call optimization (TCO).
111
112Some of the features supported by CHICKEN:
113
114* Lightweight threads based on first-class continuations
115* Record structures
116* Extended comment- and string-literal syntaxes
117* Libraries for regular expressions, string handling
118* UNIX system calls and extended data structures
119* Compiled C files can be easily distributed
120* Allows the creation of fully self-contained statically linked executables
121* On systems that support it, compiled code can be loaded dynamically
122* Built-in support for cross-compilation
123
124CHICKEN has been used in many environments ranging from embedded
125systems through desktop machines to large-scale server deployments.
126The number of language extensions, or '''eggs''', is constantly growing:
127
128* extended language features
129* development tools, such as documentation generators, debugging, and
130 automated testing libraries
131* interfaces to other languages such as Java, Python, and Objective-C
132* interfaces to database systems, GUIs, and other libraries,
133* network applications, such as servers and clients for ftp,
134 smtp/pop3, irc, and http
135* web servers and related tools, including URL parsing, HTML
136 generation, AJAX, and HTTP session management
137* data formats, including XML, JSON, and Unicode support
138
139This chapter provides you with an overview of the entire system, with
140enough information to get started writing and running small Scheme
141programs.
142
143=== CHICKEN repositories, websites and community
144
145The master CHICKEN website is
146[[http://www.call-cc.org]]. Here you can find
147basic information about CHICKEN, downloads and pointers to other key
148resources.
149
150The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most
151current version of the User's manual, along with various tutorials and
152other useful documents. The list of eggs is at
153[[http://wiki.call-cc.org/egg-index|http://wiki.call-cc.org/egg-index]].
154
155A very useful search facility for questions about procedures and syntax
156available for CHICKEN can be found at
157[[http://api.call-cc.org]]. The CHICKEN issue tracker is at
158[[http://bugs.call-cc.org]].
159
160The CHICKEN community has two major mailing lists. If you are a
161CHICKEN user, {{chicken-users}}
162([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be
163of interest. The crew working on the CHICKEN system itself uses the
164very low-volume {{chicken-hackers}} list
165([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for
166communication. For other topic-specific mailing lists (e.g.,
167announcements, security) and discussion groups, see
168[[http://wiki.call-cc.org/discussion-groups|http://wiki.call-cc.org/discussion-groups]].
169
170There is also an IRC channel ({{#chicken}}) on
171[[http://libera.chat|Libera.Chat]].
172
173=== Installing CHICKEN
174
175CHICKEN is available as C sources. Refer to the
176{{README}} file in the distribution for instructions on installing it
177on your system.
178
179Because it compiles to C, CHICKEN requires that a C compiler be
180installed on your system. (If you're not writing embedded C code, you
181can pretty much ignore the C compiler once you have installed it.)
182
183* On a Linux system, a C toolchain (e.g., GCC, clang) should be
184 installed as part of the basic operating system, or should be
185 available through the package management system (e.g., APT,
186 Synaptic, RPM, or Yum, depending upon your Linux distribution).
187* On Macintosh OS X, you will need the XCode tools, which are
188 installable from the App Store.
189* On Windows, you have three choices:
190* Cygwin ([[https://www.cygwin.com/]]) provides a relatively
191 full-featured Unix environment for Windows. CHICKEN works
192 substantially the same in Cygwin and Unix.
193* The GNU Compiler Collection has been ported to Windows, in the
194 MinGW system ([[http://mingw-w64.org/]]). Unlike Cygwin,
195 executables produced with MinGW do not need the Cygwin DLLs in order
196 to run. MSYS is a companion package to MinGW; it provides a minimum
197 Unix-style development/build environment, again ported from free
198 software.
199* You can build CHICKEN either with MinGW alone or with MinGW plus
200 MSYS. Both approaches produce a CHICKEN built against the mingw headers
201 and libraries.
202 The only difference is the environment where you actually run make.
203 {{Makefile.mingw}} can be used in {{cmd.exe}} with the version of make
204 that comes with mingw. {{Makefile.mingw-msys}}
205 uses unix commands such as {{cp}} and {{rm}}. The end product is the
206 same.
207
208Refer to the {{README}} file for the version you're installing for
209more information on the installation process.
210
211Alternatively, third party packages in binary format are
212available. See
213[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]
214for information about how to obtain them.
215
216=== Development environments
217
218The simplest development environment is a text editor and terminal
219window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
220using the interpreter and/or invoking the compiler. If you install one
221of the line editing extensions (e.g., [[/egg/breadline|breadline]], [[/egg/linenoise|linenoise]]), you have some
222useful command line editing features in the interpreter (e.g., Emacs
223or vi-compatible line editing, customization).
224
225It will be helpful to use a text editor that knows Scheme; it can be painful
226with editors that don't do parenthesis matching and automatic
227indentation.
228
229In the rest of this chapter, we'll assume that you are using an editor
230of your choice and a regular terminal window for executing your
231CHICKEN code.
232
233=== The Read-Eval-Print loop
234
235To invoke the CHICKEN interpreter, you use the {{csi}} command.
236
237 $ csi
238 CHICKEN
239 (c) 2008-2021, The CHICKEN Team
240 (c) 2000-2007, Felix L. Winkelmann
241 Version 5.3.0 (rev e31bbee5)
242 linux-unix-gnu-x86-64 [ 64bit dload ptables ]
243
244 Type ,? for help.
245 #;1>
246
247This brings up a brief banner, and then the prompt. You can use this
248pretty much like any other Scheme system, e.g.,
249
250 #;1> (define (twice f) (lambda (x) (f (f x))))
251 #;2> ((twice (lambda (n) (* n 10))) 3)
252 300
253
254Suppose we have already created a file {{fact.scm}} containing a
255function definition.
256
257 (define (fact n)
258 (if (= n 0)
259 1
260 (* n (fact (- n 1)))))
261
262We can now load this file and try out the function.
263
264 #;3> (load "fact.scm")
265 ; loading fact.scm ...
266 #;4> (fact 3)
267 6
268
269The '''read-eval-print loop''' ('''REPL''') is the component of the
270Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
271and ''prints'' out the result. The REPL's prompt can be customized
272(see the [[Using the interpreter]])
273but the default prompt, showing the number of the form, is quite
274convenient.
275
276The REPL also supports debugging commands:
277input lines beginning with a {{,}} (comma) are treated as special
278commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
279
280
281==== Scripts
282
283You can use the interpreter to run a Scheme program from the command
284line. For the following example we create a program that does a quick
285search-and-replace on an input file; the arguments are a regular
286expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
287
288 xyzabcghi
289 abxawxcgh
290 foonly
291
292Next create the scheme code in a file called ''quickrep.scm'' with the
293following little program:
294
295<enscript highlight=scheme>
296;; irregex, the regular expression library, is one of the
297;; libraries included with CHICKEN.
298(import (chicken irregex)
299 (chicken io))
300
301(define (process-line line re rplc)
302 (irregex-replace/all re line rplc))
303
304(define (quickrep re rplc)
305 (let ((line (read-line)))
306 (if (not (eof-object? line))
307 (begin
308 (display (process-line line re rplc))
309 (newline)
310 (quickrep re rplc)))))
311
312;;; Does a lousy job of error checking!
313(define (main args)
314 (quickrep (irregex (car args)) (cadr args)))
315</enscript>
316
317
318To run it enter this in your shell:
319
320 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
321 xyzAghi
322 Agh
323 foonly
324
325The {{-ss}} option sets several options that work smoothly together to
326execute a script. You can make the command directly executable from
327the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]
328at the beginning of the program.
329
330The {{-ss}} option arranges to call a procedure named {{main}}, with
331the command line arguments, packed in a list, as its arguments. (There
332are a number of ways this program could be made more idiomatic CHICKEN
333Scheme, see the rest of the manual for details.)
334
335=== The compiler
336
337There are several reasons you might want to compile your code.
338
339* Compiled code executes substantially faster than interpreted
340 code.
341* You might want to deploy an application onto machines where the
342 users aren't expected to have CHICKEN installed: compiled
343 applications can be self-contained.
344* Compiled code can access external libraries written in lower-level
345 languages that follow the C calling convention.
346
347The CHICKEN compiler is provided as the command {{chicken}}, but in
348almost all cases, you will want to use the {{csc}} command
349instead. {{csc}} is a convenient driver that automates compiling
350Scheme programs into C, compiling C code into object code, and linking
351the results into an executable file. (Note: in a Windows environment
352with Visual Studio, you may find that {{csc}} refers to Microsoft's
353C# compiler. There are a number of ways of sorting this out, of which
354the simplest is to rename one of the two tools, and/or to
355organize your {{PATH}} according to the task at hand.)
356
357We can compile our factorial function, producing a file named
358{{fact.so}} (''shared object'' in Linux-ese, the same file extension is
359used in Windows, rather than {{dll}})
360
361 chicken$ csc -shared fact.scm
362 chicken$ csi -quiet
363 #;1> (load "fact.so")
364 ; loading fact.so ...
365 #;2> (fact 6)
366 720
367
368On any system, we can just compile a program directly into an
369executable. Here's a program that tells you whether its argument is a
370palindrome.
371
372<enscript highlight=scheme>
373(import (chicken process-context)) ; for "command-line-arguments"
374
375(define (palindrome? x)
376 (define (check left right)
377 (if (>= left right)
378 #t
379 (and (char=? (string-ref x left) (string-ref x right))
380 (check (add1 left) (sub1 right)))))
381 (check 0 (sub1 (string-length x))))
382
383(let ((arg (car (command-line-arguments))))
384 (display
385 (string-append arg
386 (if (palindrome? arg)
387 " is a palindrome\n"
388 " isn't a palindrome\n"))))
389</enscript>
390
391We can compile this program using {{csc}}, creating an executable
392named {{palindrome}}.
393
394 $ csc -o palindrome palindrome.scm
395 $ ./palindrome level
396 level is a palindrome
397 $ ./palindrome liver
398 liver isn't a palindrome
399
400CHICKEN supports separate compilation, using some extensions to
401Scheme. Let's divide our palindrome program into a library module
402({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
403
404Here's the external library. We {{declare}} that {{pal-proc}} is a
405''unit'', which is the basis of separately-compiled modules in
406CHICKEN. (Units deal with separate compilation, but don't necessarily
407involve separated namespaces; namespaces can be implemented by
408[[/manual/Modules|modules]].)
409
410<enscript highlight=scheme>
411;;; Library pal-proc.scm
412(declare (unit pal-proc))
413
414(define (palindrome? x)
415 (define (check left right)
416 (if (>= left right)
417 #t
418 (and (char=? (string-ref x left) (string-ref x right))
419 (check (add1 left) (sub1 right)))))
420 (check 0 (sub1 (string-length x))))
421</enscript>
422
423Next we have some client code that ''uses'' this separately-compiled
424module.
425
426<enscript highlight=scheme>
427;;; Client pal-user.scm
428(declare (uses pal-proc))
429
430(import (chicken process-context))
431
432(let ((arg (car (command-line-arguments))))
433 (display
434 (string-append arg
435 (if (palindrome? arg)
436 " is a palindrome\n"
437 " isn't a palindrome\n"))))
438</enscript>
439
440Now we can compile and link everything together. (We show the compile
441and link operations separately, but they can of course be combined
442into one command.)
443
444 $ csc -c pal-proc.scm
445 $ csc -c pal-user.scm
446 $ csc -o pal-separate pal-proc.o pal-user.o
447 $ ./pal-separate level
448 level is a palindrome
449
450The "unit" mechanism is relatively low-level and requires some
451familiarity with underlying mechanism used to manage compilation
452units. See [[Units and linking model]] for more information.
453
454=== Installing an egg
455
456Installing eggs is quite straightforward on systems that support
457dynamic loading (that would include *BSD, Linux, Mac OS X,
458Solaris, and Windows). The command {{chicken-install}} will fetch an
459egg from the master CHICKEN repository, and install it on your local
460system.
461
462In this example, we install the {{uri-common}} egg, for parsing
463Uniform Resource Identifiers.
464
465 $ chicken-install uri-common
466
467{{chicken-install}} connects to a mirror of the egg repository and
468retrieves the egg contents. If the egg has any uninstalled
469dependencies, it recursively installs them. Then it builds the egg
470code and installs the resulting extension into the
471local CHICKEN repository.
472
473Now we can use our new egg.
474
475 #;1> (import uri-common)
476 ; loading /usr/lib/chicken/9/uri-common.import.so ...
477 ; [... other loaded files omitted for clarity ...]
478
479 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
480 "www.foobar.org"
481
482=== Accessing C libraries
483
484Because CHICKEN compiles to C, and because a foreign function
485interface is built into the compiler, interfacing to a C library is
486quite straightforward. This means that any facility available
487on the host system is accessible from CHICKEN, with more or less
488work.
489
490Let's create a simple C library, to demonstrate how this
491works. Here we have a function that will compute and return the '''n'''th
492Fibonacci number. (This isn't a particularly good use of C here,
493because we could write this function just as easily in Scheme, but a
494real example would take far too much space here.)
495
496 /* fib.c */
497 int fib(int n) {
498 int prev = 0, curr = 1;
499 int next;
500 int i;
501 for (i = 0; i < n; i++) {
502 next = prev + curr;
503 prev = curr;
504 curr = next;
505 }
506 return curr;
507 }
508
509Now we can call this function from CHICKEN.
510
511 ;;; fib-user.scm
512 (import (chicken foreign) (chicken format))
513
514 #>
515 extern int fib(int n);
516 <#
517 (define xfib (foreign-lambda int "fib" int))
518 (do ((i 0 (+ i 1))) ((> i 10))
519 (printf "~A " (xfib i)))
520 (newline)
521
522The syntax {{#>...<#}} allows you to include literal C (typically
523external declarations) in your CHICKEN code. We access {{fib}} by
524defining a {{foreign-lambda}} for it, in this case saying that the
525function takes one integer argument (the {{int}} after the function
526name), and that it returns an integer result (the {{int}} before.) Now we can invoke
527{{xfib}} as though it were an ordinary Scheme function.
528
529 $ gcc -c fib.c
530 $ csc -o fib-user fib.o fib-user.scm
531
532If using MinGW on Windows,
533
534 > gcc -c fib.c -o fib.obj
535 > csc -o fib-user fib.obj fib-user.scm
536
537Then run the executable.
538 $ ./fib-user
539 0 1 1 2 3 5 8 13 21 34 55
540
541Those who are interfacing to substantial C libraries should consider
542using the [[/egg/bind|bind egg]].
543
544---
545
546Back to [[The User's Manual]]
547
548Next: [[Using the interpreter]]